<template>
  <view class="main">
    <component class="component" :is="curPage" />
    <tab-bar-overturn @change="changePage" :fixed-bottom="true" :tab-list=tabList></tab-bar-overturn>
  </view>
</template>

<script>
import tabBarOverturn from "@/uni_modules/helang-tabBar/components/helang-tabBar/tab-bar-overturn";
import menuApi from "@/api/sys/menu";
import APP_CONFIG from "@/config/config";
import setup from "@/pages/modules/sys/setup/setup";
import workbench from "@/pages/modules/sys/workbench/workbench";

import toolApi from "@/api/toolApi";
import dictTypeApi from "@/api/sys/dictType";
import silenceUpdate from "@/uni_modules/rt-uni-update/js_sdk/silence-update";
import websocket from "@/utils/websocket";
import modulesLogi from "@/common/modulesLogic";


export default {
  components: {
    tabBarOverturn,
    setup,
    workbench,
  },
  data() {
    return {
      title: 'Hello',
      curPage: '',
      userInfo: {},
      scheduledTask: true,
      tabList: [
        {
          "icon": "home",
          "iconSelected": "home-filled",
          "text": "首页",
          "url": "page1"
        },
        {
          "icon": "chat",
          "iconSelected": "chat-filled",
          "text": "消息",
          "url": "page2"
        },
        {
          "icon": "gift",
          "iconSelected": "gift-filled",
          "text": "工具"
        },
        {
          "icon": "person",
          "iconSelected": "person-filled",
          "text": "我的"
        },
      ],
    }
  },
  async onLoad() {
    await this.getUserInfo()
    await this.getNav()
    await modulesLogi.onLoad();
  },
  beforeDestroy (){
  },
  async onShow() {
    //#ifdef APP-PLUS
    plus.push.clear();
    //#endif

    //#ifdef APP-PLUS

    //获取本地应用资源版本号
    plus.runtime.getProperty(plus.runtime.appid, (inf) => {
      console.log(inf, inf.version)
      toolApi.getVersion().then(res => {
        let renew = false
        if (res.data.edition_number && inf.version) {
          let edition_number = res.data.edition_number.split(".")
          let version = inf.version.split(".")
          renew = this.compare(edition_number, version)
        }
        //res.data.xxx根据后台返回的数据决定（我这里后端返回的是data），所以是res.data.data
        //判断后台返回版本号是否大于当前应用版本号 && 是否发行 （上架应用市场时一定不能弹出更新提示）
        if (renew) {

          //如果是wgt升级，并且是静默更新 （注意！！！ 如果是手动检查新版本，就不用判断静默更新，请直接跳转更新页，不然点击检查新版本后会没反应）
          if (res.data.package_type === 1 && res.data.edition_silence === 1) {
            //调用静默更新方法 传入下载地址
            silenceUpdate(res.data.edition_url)

          } else {
            //跳转更新页面 （注意！！！如果pages.json第一页的代码里有一打开就跳转其他页面的操作，下面这行代码最好写在setTimeout里面设置延时3到5秒再执行）
            uni.navigateTo({
              url: '/uni_modules/rt-uni-update/components/rt-uni-update/rt-uni-update?obj=' +
                  JSON.stringify(res.data)
            });
          }
        } else {
          // 如果是手动检查新版本 需开启以下注释
          /* uni.showModal({
              title: '提示',
              content: '已是最新版本',
              showCancel: false
          }) */
        }
      })
    });

    //#endif
  },
  methods: {
    async getUserInfo() {
      await dictTypeApi.getTreeDict().then(resdict => {
        if (resdict.success) {
          uni.setStorageSync('dictionaries', resdict.data)

          //如果状态正常且未连接
          if (!websocket.isConnection() && resdict.code !== '106'){
            websocket.connectWebsocket()
          }
        }
      })
    },
    /**
     * 获取菜单
     * */
    async getNav() {
      await menuApi.getNav().then(resnav => {
        if (resnav && resnav.success) {
          let nav = this.navTreeToList(resnav.data.nav)
          if (nav && nav.length > 2) {
            nav = nav.slice(0, 2)
          }
          nav.push({
            component: null,
            icon: "tune",
            iconSelected: "tune-filled",
            id: "otherMenu",
            text: "工具",
            url: "/sys/workbench",
            perms: "",
            sort: 1,
            type: 1,
          })
          nav.push({
            component: null,
            icon: "person",
            iconSelected: "person-filled",
            id: "setup",
            text: "我的",
            url: "/sys/setup",
            perms: "",
            sort: 1,
            type: 1,
          })
          this.tabList = nav

          if (nav && nav.length > 0) {
            this.changePage(nav[0])
          }
          uni.setStorageSync('permission', resnav.data.authoritys)
        }
      })
    },
    navTreeToList(menuTree) {
      let menus = []
      if (menuTree) {
        for (let item of menuTree) {
          if (item.type === 1) {
            item.text = item.name
            item.icon = item.vantIcon
            item.iconSelected = item.vantIcon + '-filled'
            item.url = item.path
            menus.push(item)
          }
          if (item.children && item.children.length > 0) {
            let childIds = this.navTreeToList(item.children)
            menus = menus.concat(childIds)
          }
        }
      }
      return menus
    },
    /**
     * 切换页面
     * */
    changePage(e) {
      if (e.url) {
        this.curPage = e.url.lastIndexOf('/') > -1 ? e.url.substring(e.url.lastIndexOf('/') + 1) : e.url
      }
    },
    /**
     * 递归比较
     * */
    compare(one, two){
      if (one && one.length > 0){
        if (!two || two.length === 0){
          return true
        }
        let oneZ = Number(one[0])
        let twoZ = Number(two[0])
        if (oneZ > twoZ){
          return true
        }else if (oneZ < twoZ){
          return false
        }else if (oneZ === twoZ && one.length > 1){
          one.shift()
          two.shift()
          return this.compare(one, two)
        }else{
          return false
        }
      }
      return false;
    },
  }
}
</script>

<style lang="scss">
//page {
//  height: 100%;
//}
.main{
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.component{
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  //overflow-y: auto;
  box-sizing: border-box;
}
</style>
